package leetcode.ArrayAndString;

public class TwoSum {

    public static int[] twoSum(int[] numbers, int target) {
        int[] result = null;
        for (int i = 0; i < numbers.length; i++) {
            int a = target - numbers[i];
            // 二分查找
            int left = i + 1;
            int right = numbers.length - 1;


            while (true) {
                int mid = (left + right) / 2;
                if (a > numbers[mid]) {
                    left = mid + 1;

                } else if (a < numbers[mid]) {
                    right = mid - 1;
                } else {
                    result = new int[2];
                    result[0] = i + 1;
                    result[1] = mid + 1;
                    return result;
                }

                if (left > right) {
                    break;
                }
            }

        }
        return result;
    }

    public int[] betterTwoSum(int[] numbers, int target) {
        //双指针
        int p1 = 0;
        int p2 = numbers.length - 1;
        while (p1 < p2) {
            while (numbers[p1] + numbers[p2] > target) {
                p2--;
            }
            if (numbers[p1] + numbers[p2] == target) {
                return new int[]{p1 + 1, p2 + 1};
            }
            while (numbers[p1] + numbers[p2] < target) {
                p1++;
            }
        }
        return new int[2];
    }


    public static void main(String[] args) {
        int[] nums = {1, 2, 4, 5};
        int target = 6;
        System.out.println(twoSum(nums, target)[0]);
        System.out.println(twoSum(nums, target)[1]);

    }
}
